<template>
  <view class="page">
    <view class="cen-box">
      <u--form
        labelPosition="left"
        :model="newParams"
        ref="newParamsRef"
        labelWidth="160"
      >
        <view class="jc">
          <view class="head">基本信息</view>
          <u-form-item
            label="入住方式"
            borderBottom
            prop="newParams.ReceiveType"
          >
            <view>
              {{
                receiveTypes.filter(
                  (item) => item.id === newParams.ReceiveType
                )[0].name
              }}
            </view>
          </u-form-item>
          <u-form-item
            label="入住类型"
            borderBottom
            prop="newParams.ReceiveClass"
            @click="popup_change(true, '入住类型')"
          >
            <view>
              {{
                ReceiveClassOptions_columns.filter(
                  (item) => item.value === newParams.ReceiveClass
                )[0].name
              }}
            </view>
            <template #right>
              <u-icon name="arrow-right"></u-icon>
            </template>
          </u-form-item>
          <u-form-item
            label="入住天数"
            borderBottom
            prop="newParams.Days"
            v-if="newParams.ReceiveClass !== 'DU'"
          >
            <u-number-box
              button-size="60"
              inputWidth="200"
              v-model="newParams.Days"
            ></u-number-box>
          </u-form-item>
          <view v-else>
            <u-form-item
              label="入住时长"
              borderBottom
              prop="newParams.Duration"
            >
              <u-number-box
                button-size="60"
                inputWidth="200"
                v-model="newParams.Duration"
              ></u-number-box>
            </u-form-item>
            <u-form-item
              label="超时价"
              borderBottom
              prop="newParams.HourTimeoutPrice"
            >
              <u-number-box
                button-size="60"
                inputWidth="200"
                v-model="newParams.HourTimeoutPrice"
              ></u-number-box>
            </u-form-item>
          </view>
          <u-form-item label="抵离时间" borderBottom prop="dateTimeOptions">
            <uni-datetime-picker
              v-model="dateTimeOptions"
              :border="false"
              type="daterange"
              @change="change_dateTimeOptions"
              :start="dateTimeOptions[0]"
              rangeSeparator="/"
            />
          </u-form-item>
          <u-form-item
            label="客源类型"
            borderBottom
            prop="newParams.TheClass"
            @click="popup_change(true, '客源类型')"
          >
            <view>{{ newParams.TheClass }}</view>
            <template #right>
              <u-icon name="arrow-right"></u-icon>
            </template>
          </u-form-item>
        </view>

        <view
          class="jc"
          v-for="(item, index) in newParams.Rooms"
          :key="index"
          @click="change_chooseRoomIndex(index)"
        >
          <view>
            <view class="head justify-between">
              <view>入住信息 {{ index + 1 }}</view>
              <u-icon
                name="trash"
                @click="onDelRoom(index)"
                customStyle="color: #84878c"
              ></u-icon>
            </view>

            <u-form-item
              label="选择房间"
              borderBottom
              prop="item.RoomNo"
              @click="onChooseRoomNo(item.RoomClass)"
            >
              <view v-if="item.RoomNo">
                {{ item.RoomClass }}/{{ item.RoomNo }}
              </view>
              <view v-else>请选择房间</view>
              <template #right>
                <u-icon name="arrow-right"></u-icon>
              </template>
            </u-form-item>

            <u-form-item label="优惠价" borderBottom prop="item.Price">
              <view v-if="item.Price">{{ item.Price }}</view>
            </u-form-item>

            <u-form-item
              label="添加入住人"
              borderBottom
              prop="item.RoomClassId"
              @click="popup_change(true, '添加入住人')"
            >
              <template #right>
                <u-icon name="arrow-right"></u-icon>
              </template>
            </u-form-item>
          </view>
        </view>

        <view class="jc btn-new" @click="onAddRoom">
          <u-icon
            size="32"
            color="#2891FA"
            name="plus-circle"
            label="添加房间"
            labelPos="right"
            labelSize="32"
            labelColor="#2891FA"
          ></u-icon>
        </view>

        <view class="jc">
          <view class="head">收款</view>
          <u-form-item
            label="支付方式"
            @click="popup_change(true, '支付方式')"
            borderBottom
            prop="newParams.PaymentMethod"
          >
            <view>
              {{
                payList.filter((item) => item.Id === newParams.PaymentMethod)[0]
                  ?.Name
              }}
            </view>
            <template #right>
              <u-icon name="arrow-right"></u-icon>
            </template>
          </u-form-item>
          <u-form-item
            label="支付金额"
            borderBottom
            prop="newParams.PaymentPrice"
          >
            <u--input
              @change="change_PaymentPrice"
              prefixIcon="rmb"
              prefixIconStyle="font-size: 40rpx;color: #909399"
              v-model="newParams.PaymentPrice"
              type="number"
              placeholder="请输入支付金额"
            ></u--input>
          </u-form-item>
        </view>
      </u--form>
    </view>

    <view
      class="scope-button justify-around align-center"
      @click="onNewCheckIn"
    >
      确认入住
    </view>

    <u-popup
      :show="popup_show"
      :round="30"
      closeable
      customStyle="max-height: 60vh;"
      mode="bottom"
      @close="popup_change(false)"
    >
      <view class="popup_header">
        <view class="title">
          {{ popup_type }}
        </view>
      </view>
      <view class="popup_content">
        <view v-if="popup_type === '入住类型'">
          <u-radio-group
            v-model="newParams.ReceiveClass"
            placement="column"
            iconPlacement="right"
            :borderBottom="true"
          >
            <u-radio
              labelSize="30"
              :customStyle="radioStyle"
              iconSize="30"
              size="30"
              v-for="item in ReceiveClassOptions_columns"
              :key="item.id"
              :label="item.name"
              :name="item.value"
            ></u-radio>
          </u-radio-group>
        </view>
        <view v-else-if="popup_type === '客源类型'">
          <u-radio-group
            v-model="newParams.TheClass"
            placement="column"
            iconPlacement="right"
            :borderBottom="true"
          >
            <u-radio
              labelSize="30"
              :customStyle="radioStyle"
              iconSize="30"
              size="30"
              v-for="item in TheClassList"
              :key="item.Id"
              :label="item.Id"
              :name="item.Id"
            ></u-radio>
          </u-radio-group>
        </view>

        <view v-else-if="popup_type === '选择房间'">
          <!--          <u-radio-group-->
          <!--            v-model="newParams.Rooms[chooseRoomIndex].RoomNo"-->
          <!--            placement="column"-->
          <!--            iconPlacement="right"-->
          <!--            :borderBottom="true"-->
          <!--          >-->
          <!--            <u-radio-->
          <!--              labelSize="30"-->
          <!--              :customStyle="radioStyle"-->
          <!--              iconSize="30"-->
          <!--              size="30"-->
          <!--              v-for="item in can_choose_RoomNos"-->
          <!--              :key="item"-->
          <!--              :label="item"-->
          <!--              :name="item"-->
          <!--            ></u-radio>-->
          <!--          </u-radio-group>-->

          <view
            v-for="i in 3"
            style="padding-bottom: 40rpx; padding-left: 30rpx"
          >
            <view class="roomClass">精品双床房</view>
            <view class="flex-wrap">
              <view
                class="roomNo flex-center"
                v-for="item in [8801, 8802, 8803, 8804, 8805]"
              >
                {{ item }}
              </view>
            </view>
          </view>
        </view>
        <view v-else-if="popup_type === '支付方式'">
          <u-radio-group
            v-model="newParams.PaymentMethod"
            placement="column"
            iconPlacement="right"
            :borderBottom="true"
          >
            <u-radio
              labelSize="30"
              :customStyle="radioStyle"
              iconSize="30"
              size="30"
              v-for="item in payList"
              :key="item.Id"
              :label="item.Name"
              :name="item.Id"
            ></u-radio>
          </u-radio-group>
        </view>
        <view
          v-else-if="popup_type === '添加入住人'"
          style="background: #f5f5f5"
        >
          <u--form
            labelPosition="left"
            :model="newParams.Rooms[chooseRoomIndex]"
            ref="ReceiveManRef"
            labelWidth="160"
          >
            <view
              class="jc"
              style="margin: 0 0 30rpx"
              v-for="(item, index) in newParams.Rooms[chooseRoomIndex]
                .ReceiveMan"
            >
              <view class="head">入住人 {{ index + 1 }}</view>
              <u-form-item label="姓名" borderBottom>
                <u--input
                  v-model="item.Name"
                  :max="20"
                  placeholder="请输入姓名"
                ></u--input>
              </u-form-item>
              <u-form-item label="手机号" borderBottom>
                <u--input
                  v-model="item.Tel"
                  placeholder="请输入手机号"
                ></u--input>
              </u-form-item>
              <u-form-item label="早餐" borderBottom>
                <u-number-box
                  :min="0"
                  button-size="60"
                  inputWidth="200"
                  v-model="item.BreakFastNum"
                ></u-number-box>
              </u-form-item>
              <u-form-item label="身份证号码" borderBottom>
                <u--input
                  v-model="item.Code"
                  placeholder="请输入手机号"
                ></u--input>
              </u-form-item>
            </view>
          </u--form>
          <view class="jc btn-new" @click="onAddReceiveMan">
            <u-icon
              size="32"
              color="#2891FA"
              name="plus-circle"
              label="新增同住人"
              labelPos="right"
              labelSize="32"
              labelColor="#2891FA"
            ></u-icon>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from 'vue'
import {
  INF_NewParams,
  receiveMan,
  receiveParams,
  receiveRoomInfo
} from '@/receivePages/pre/initState'
import { ReceiveClassOptions } from '@/receivePages/pre/initState'
import { GetManclass, INF_GetManclass_res } from '@/api/server/v1/book'
import { onLoad } from '@dcloudio/uni-app'
import toast from '@/utils/toast'
import {
  GetFreeRoomForCheckInV1,
  HU,
  IfCanCheckIn,
  INF_GetFreeRoomForCheckInV1_params,
  INF_GetFreeRoomForCheckInV1_res,
  INF_IfCanCheckIn_params,
  INF_NewCheckIn_res,
  NewCheckIn
} from '@/api/server/v1/receive'
import route from '@/utils/route'
import {
  defaultPayClass,
  GetPayClass,
  INF_GetPayClass_res
} from '@/api/server/v2/pay'
import { receivePage_detail } from '@/route'
import {
  GetCompanyListV1,
  GetVipList,
  INF_GetCompanyListV1_res,
  INF_GetVipList_res
} from '@/api/server/v1/user'

// 如果是新入住，则直接入住查询HomeClass拿到列表，等选择房型，是空的，然后再去匹配
// 如果是有params传参的，则直接传递整个数据，主要是房型和房号。
onLoad((params) => {
  const routeParams = params as TYPE_routeParams
  const { TheClassId } = routeParams
  if (TheClassId) {
    // 房态图进来的
    const params: INF_IfCanCheckIn_params = { id: Number(TheClassId) }
    IfCanCheckIn(params)
      .then(() => {
        newParams.Rooms[0].RoomNo = routeParams.RoomNo
        newParams.Rooms[0].RoomClass = routeParams.RoomClass
        newParams.Rooms[0].Price = routeParams.Price
      })
      .catch(() => {
        toast.$toast('该房间不可以办理入住,正在返回...')
        setTimeout(() => {
          route.$route_back()
        }, 3000)
      })

    // const data: INF_GetFreeRoomForCheckInV1_params = {
    //   Hid: 0, // 散客等于0
    //   WillLeave: newParams.WillLeave
    // }
    // // 匹配当前房型下到底还有无可排房的房间
    // GetFreeRoomForCheckInV1(data).then((res) => {
    //   const room_class_list = res as Array<INF_GetFreeRoomForCheckInV1_res>
    //   for (let item of room_class_list) {
    //     if (item.HomeClassId === TheClassId) {
    //       //   当前选择的房型和查询可用房型匹配的话，可以接着选择可用的房型下的房间号了
    //       can_choose_RoomNos.value = item.RoomNos
    //       newParams.Rooms[chooseRoomIndex.value].Price = item.Price
    //     }
    //   }
    // })
  }
  if (!TheClassId) {
  }

  // 客源类型列表
  GetManclass().then((res) => {
    const result = res as Array<INF_GetManclass_res>
    TheClassList.value = result
  })
  // 支付方式列表
  GetPayClass().then((res) => {
    payList.value = res as INF_GetPayClass_res[]
  })
  GetCompanyListV1().then((res) => {
    console.log('协议单位列表', res)
    companyList.value = res as Array<INF_GetCompanyListV1_res>
  })
  GetVipList().then((res) => {
    console.log(res, '会员列表')
    vipList.value = res as Array<INF_GetVipList_res>
  })
})

const payList = ref<INF_GetPayClass_res[]>([defaultPayClass])
type TYPE_routeParams = {
  readonly TheClassId: string
  readonly RoomClass: string
  readonly RoomNo: string
  readonly Price: number
}
type TYPE_receiveType = { name: string; value: 'Ordinary' | 'Team'; id: number }
const receiveTypes = ref<Array<TYPE_receiveType>>([
  {
    name: '普通预订',
    value: 'Ordinary',
    id: 0
  },
  {
    name: '团队预订',
    value: 'Team',
    id: 1
  }
])

// 客源类型里“协议单位”的列表
const companyList = ref<Array<INF_GetCompanyListV1_res>>([])
// 客源类型里“会员”的列表
const vipList = ref<Array<INF_GetVipList_res>>([])
// 客源类型的列表
const TheClassList = ref<Array<INF_GetManclass_res>>([])
// 可入住的房型列表，每一项都有房间列表
const HomeClassList = ref<Array<INF_GetFreeRoomForCheckInV1_res>>([])

const newParams = reactive<INF_NewParams>(receiveParams())
const dateTimeOptions = ref<string[]>([
  new Date().toLocaleDateString(),
  addTwelveHours(new Date())
])

// 当前正在操作的房间索引
const chooseRoomIndex = ref<number>(0)

const can_choose_RoomNos = ref<string[]>([])

const change_chooseRoomIndex = function (index: number) {
  chooseRoomIndex.value = index
}

// 日期的切换
const change_dateTimeOptions = function (arr: Array<string>) {
  newParams.WillLeave = arr[1]
  for (let item of newParams.Rooms) {
    for (let i of item.ReceiveMan) {
      i.CheckIn = arr[0]
      i.CheckOut = arr[1]
    }
  }
  // 	这里赋值日期组件
}

change_dateTimeOptions(dateTimeOptions.value) // 第一次先自己调用，让里面参数赋值

// 支付金额如果是负数则归零
const change_PaymentPrice = function () {
  console.log(newParams.PaymentPrice, '当前的')
  if (newParams.PaymentPrice < 0) {
    newParams.PaymentPrice = 0
    console.log(newParams.PaymentPrice, '更改的')
  }
}

const onDelRoom = function (index: number) {
  newParams.Rooms.splice(index, 1)
}

const onAddRoom = function () {
  newParams.Rooms.push(receiveRoomInfo())
}

const onAddReceiveMan = function () {
  newParams.Rooms[chooseRoomIndex.value].ReceiveMan.push(receiveMan())
}

// 工具函数，接受一个日期时间参数，并返回加上12小时后的日期时间值
function addTwelveHours(dateTime: Date): string {
  const newDateTime = new Date(dateTime)
  newDateTime.setHours(newDateTime.getHours() + 12)
  newDateTime.setMinutes(0)
  newDateTime.setSeconds(0)
  newDateTime.setMilliseconds(0)

  // 获取日期部分的字符串
  const datePart = newDateTime.toISOString().split('T')[0]

  // 获取时间部分的小时，确保分钟和秒钟都为零
  const hours = newDateTime.getHours()

  // 返回日期和时间组合的字符串，分钟和秒钟都设置为"00"
  return `${datePart} ${hours}:00:00`
}

// 选择房间前必须要先选择房型，才有对应的房间
const onChooseRoomNo = function (RoomClass: string) {
  // HomeClassList
  if (can_choose_RoomNos.value.length === 0) {
    //   说明没用赋值RoomNos
    for (let item of HomeClassList.value) {
      if (item.HomeName === RoomClass) {
        const data: INF_GetFreeRoomForCheckInV1_params = {
          WillLeave: newParams.WillLeave,
          Hid: 0 // 散客是0
        }
        GetFreeRoomForCheckInV1(data).then((res) => {
          const list = res as Array<INF_GetFreeRoomForCheckInV1_res>
          for (let item of list) {
            if (item.HomeName === RoomClass) {
              can_choose_RoomNos.value = item.RoomNos
              newParams.Rooms[chooseRoomIndex.value].Price = item.Price // 房价是房型的价格
            }
          }
        })
      }
    }
  }
  popup_change(true, '选择房间')
}

const popup_show = ref<boolean>(false)
type TYPE_popup_type =
  | '客源类型'
  | '入住类型'
  | '添加入住人'
  | '选择房间'
  | '支付方式'
  | ''
const popup_type = ref<TYPE_popup_type>('客源类型')

const ReceiveClassOptions_columns = ref(ReceiveClassOptions)

const popup_change = function (show: boolean, type: TYPE_popup_type = '') {
  popup_show.value = show
  popup_type.value = type
}

const radioStyle = reactive({ padding: '50rpx 0' })

const onNewCheckIn = function () {
  console.log(newParams, ' new')
  // return
  NewCheckIn(newParams).then((res) => {
    const { Id } = res as INF_NewCheckIn_res
    route.$route_redirect(receivePage_detail + '?id=' + Id)
  })
}

watch(
  () => newParams.ReceiveClass,
  (value: string) => {
    if (value === HU) {
      newParams.PaymentPrice = 0
    }
  },
  { immediate: true, deep: true }
)

watch(
  () => newParams.ReceiveClass,
  (value: string) => {
    if (value === HU) {
      newParams.PaymentPrice = 0
    }
  },
  { immediate: true, deep: true }
)

watch(
  () => newParams.Days,
  (value: number) => {
    if (newParams.Rooms.length > 0) {
      let totalPrice = 0
      for (let item of newParams.Rooms) {
        totalPrice += item.Price
      }
      newParams.PaymentPrice = value * totalPrice
    }
  },
  { immediate: true, deep: true }
)

watch(
  () => newParams.TheClass,
  (value: string) => {
    if (value === '会员') {
    } else if (value === '协议') {
    } else {
    }
  },
  { immediate: true, deep: true }
)

watch(
  () => newParams.TheClass,
  (value: string) => {
    console.log(value, 'va')
  },
  { immediate: true, deep: true }
)
</script>

<style lang="scss" scoped>
//
.page {
  background-color: #f7f8fa;
  //height: calc(100vh - 44px);
  overflow-y: auto;

  .jc {
    background-color: #fff;
    margin: 24rpx 0;
    padding: 32rpx;

    .head {
      color: #84878c;
      .delIcon {
        width: 30rpx;
        height: 30rpx;
      }
    }
  }

  .btn-new {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    color: #2891fa;
  }

  .cen-box {
    height: 100%;
  }
  .popup_content {
    overflow-y: scroll;
    padding: 30rpx;
  }

  .popup_header {
    padding: 20rpx 30rpx;
    .title {
      font-size: 40rpx;
      text-align: center;
      height: 80rpx;
      line-height: 80rpx;
      border-bottom: 1rpx solid #f5f5f5;
    }

    .nr-box {
      padding: 0 60rpx;
      max-height: 600rpx;
      overflow-y: auto;
    }
  }
}

.roomNo {
  width: 182rpx;
  height: 56rpx;
  margin-right: 30rpx;
  margin-top: 30rpx;
  background: #ffffff;
  border-radius: 8rpx;
  opacity: 1;
  border: 2rpx solid #e0e3e9;
}
.roomClass {
  font-size: 30rpx;
  font-family:
    Source Han Sans CN,
    Source Han Sans CN;
  font-weight: 400;
  color: #84878c;
}
.scope-button {
  width: 702rpx;
  height: 80rpx;
  margin: 30rpx auto;
  color: #ffffff;
  background: #409eff;
  border-radius: 8rpx;
}
</style>
